<template>
	<div class="user">
		<div class="contentMain">			
			<div class="title">
				<span>诊所管理</span>
			</div>
			<div class="main">
				<div class="main-right" ref="mainRight">
					<div class="searchValue">
						<div class="leftBtn">
							<el-autocomplete
								 :fetch-suggestions="querySearch"
								  placeholder="请输入诊所名称"
								  :trigger-on-focus="false"
								  @select="handleSelect"
								size="mini"
								v-model="searchValue">
								<i slot="prefix" class="el-input__icon el-icon-Ssearch"></i>
							</el-autocomplete>
							<el-button v-for="(v,i) in headerBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="handClick(i)">{{ v.title }}</el-button>
						</div>
						<div class="rightBtn">
							<el-button v-for="(v,i) in feetBtn" :key="i" :type="v.type" :disabled="v.disabled"
							:loading="loading" :icon="v.icon" size="mini" @click="feetHandClick(v,i)">{{ v.title }}</el-button>
						</div>
					</div>
					<div class="content">
						<el-table :data="tableData" 
						:header-cell-style="{ background: '#f4f4f4 !important'}" 
						 border
						 row-key='id'
						:default-expand-all="isExpandAll"
						:expand-row-keys="expandedRowKeys"
						@row-dblclick="handledbRow"
						:style="{ width: windowWidth + 'px' }"
						:tree-props="{children: 'children',hasChildren:true}"
						>
						<!-- 树形展开图标列 -->
						<el-table-column width="50" align="center">
							<template slot-scope="row">
							<i v-if="row.children && row.children.length"
							  :class="['el-icon-arrow-right', { 'is-expanded': row.expanded }]"
							  @click="toggleExpand(row)"
							  style="cursor: pointer;"></i>
							</template>
							</el-table-column>
							<el-table-column prop="status" label="状态" width="80">
								<template slot-scope="scope">
								  <el-tag 
									:type="scope.row.status === '1' ? 'success' : 'danger'" 
									size="mini"
								  >
									{{ scope.row.status === '1' ? '可用' : '禁用' }}
								  </el-tag>
								</template>
							</el-table-column>
							<el-table-column prop="id" label="CID" width="80"></el-table-column>
<!-- 							<el-table-column prop="name" label="诊所名称" width="168" align="left"></el-table-column> -->
							<el-table-column v-for="(col, inx) in tableRows" :key="inx" border='false' :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
							<!-- fixed -->
							<el-table-column fixed="left" label="序号" type="index"></el-table-column>
							<!-- edit -->
							<!-- 新增操作列 -->
							<el-table-column fixed="right" label="操作" width="120">
							  <template slot-scope="scope">
							    <el-button 
							      size="mini" 
							      type="primary" 
							      @click="handleEdit(scope.row)">
							      编辑
							    </el-button>
							  </template>
							</el-table-column>
						</el-table>
					</div>
					<div class="foot">
						<!-- 分页 -->
						<el-pagination
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						:current-page="pageNum"
						:page-sizes="[20, 50, 100]"
						:page-size="pageSize"
						:total="totalSize"
						layout="total, sizes, prev, pager, next, jumper"
						background
						>
						</el-pagination>
					</div>
				</div>
			</div>
			<!-- 新增Model -->
			<div class="addMenuDiglog">
			  <el-dialog
			        :title="dialogTitle" 
			        :visible.sync="addMenuDialog"
			        width="38%"
					:modal="false"
			        :before-close="handleClose">
			        <!-- 表单 - 使用与编辑模态框相同的布局 -->
			        <el-form 
			          ref="addForm" 
			          :model="addForm" 
			          :rules="addFormRules" 
			          label-width="120px"
			          size="mini">
			          <el-row :gutter="20">
			            <el-col :span="24">
			              <!-- 诊所名称 - 必填 -->
			              <el-form-item label="诊所名称" prop="name">
			                <el-input 
			                  v-model="addForm.name" 
			                  placeholder="请输入诊所名称"
			                  @blur="generatePinyin"
			                  @input="clearPinyinIfNameChanged">
			                </el-input>
			              </el-form-item>
			            </el-col>
			            <el-col :span="24">
			              <!-- 拼音简码 - 非必填 -->
			              <el-form-item label="拼音简码">
			                <el-input v-model="addForm.pinyin" placeholder="自动生成"></el-input>
			              </el-form-item>
			            </el-col>
			            <el-col :span="24">
			              <!-- 医疗机构编码 - 条件必填 -->
			              <el-form-item label="医疗机构编码" prop="code" :required="addForm.isInsurance == 1">
			                <el-input v-model="addForm.code" placeholder="请输入医疗机构编码"></el-input>
			              </el-form-item>
			            </el-col>
			            <el-col :span="24">
			              <!-- 诊所地址 - 非必填 -->
			              <el-form-item label="诊所地址">
			                <el-input v-model="addForm.address" placeholder="请输入诊所地址"></el-input>
			              </el-form-item>
			            </el-col>
			            <!-- 新增行：过期天数和是否医保 -->
			            <el-col :span="12">
			              <!-- 过期天数 - 必填 -->
			              <el-form-item label="过期天数" prop="expireDate">
			                <el-date-picker
			                  v-model="addForm.expireDate"
			                  type="date"
			                  placeholder="选择日期"
			                  style="width: 100%">
			                </el-date-picker>
			              </el-form-item>
			            </el-col>
			            <el-col :span="12">
			              <!-- 是否医保 - 必填 -->
			              <el-form-item label="是否医保" prop="isInsurance">
			                <el-checkbox 
			                  v-model="addForm.isInsurance"
			                  :true-label="1"
			                  :false-label="0"
			                  >
			                </el-checkbox>
			              </el-form-item>
			            </el-col>
			            <!-- 新增字段：就医地医保区划 -->
			            <el-col :span="24">
			              <el-form-item label="就医地医保区划" prop="mdtrtareaAdmvs" :required="addForm.isInsurance == 1">
			                <el-input v-model="addForm.mdtrtareaAdmvs" placeholder="请输入就医地医保区划"></el-input>
			              </el-form-item>
			            </el-col>
			            <el-col :span="24">
			              <!-- 状态 - 必填 -->
			              <el-form-item label="状态" prop="status">
			                <el-select v-model="addForm.status" placeholder="请选择状态" style="width: 100%">
			                  <el-option label="启用" value="1"></el-option>
			                  <el-option label="禁用" value="0"></el-option>
			                </el-select>
			              </el-form-item>
			            </el-col>
			          </el-row>
			        </el-form>
			        <span slot="footer" class="dialog-footer">
			          <el-button type="primary" @click="submit" size="mini" :loading="loading">确 定</el-button>
			          <el-button @click="addMenuDialog = false" size="mini">取 消</el-button>
			        </span>
			      </el-dialog>
			</div>
			<div class="editModel">
					<!-- 修改新增/编辑模态框 -->
					 <!-- 统一使用此模态框进行新增/编辑 -->
					<el-dialog
						:title="dialogTitle"
						:visible.sync="addMenuDialog"
						width="38%"
						:modal="false"
						:before-close="handleClose">
						<el-form 
							ref="addForm" 
							:model="addForm" 
							:rules="addFormRules" 
							label-width="120px"
							size="mini">
							<el-row :gutter="20">
								<el-col :span="24">
									<el-form-item label="诊所名称" prop="name">
										<el-input 
											v-model="addForm.name" 
											placeholder="请输入诊所名称"
											@blur="generatePinyin"
											@input="clearPinyinIfNameChanged">
										</el-input>
									</el-form-item>
								</el-col>
								<el-col :span="24">
									<el-form-item label="拼音简码">
										<el-input v-model="addForm.pinyin" placeholder="自动生成"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="24">
									<el-form-item label="医疗机构编码" prop="code" 
										:required="addForm.isInsurance === 1">
										<el-input v-model="addForm.code" placeholder="请输入医疗机构编码"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="24">
									<el-form-item label="诊所地址">
										<el-input v-model="addForm.address" placeholder="请输入诊所地址"></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="过期天数" prop="expireDate">
										<el-date-picker
											v-model="addForm.expireDate"
											type="date"
											placeholder="选择日期"
											style="width: 100%">
										</el-date-picker>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="是否医保" prop="isInsurance">
										<el-checkbox 
											v-model="addForm.isInsurance"
											:true-label="1"
											:false-label="0">
											是
										</el-checkbox>
									</el-form-item>
								</el-col>
								<el-col :span="24">
								<el-form-item 
									label="就医地医保区划" 
									prop="mdtrtareaAdmvs" 
									:required="addForm.isInsurance === 1">
									<el-input 
										v-model="addForm.mdtrtareaAdmvs" 
										placeholder="请输入就医地医保区划"
										:disabled="addForm.isInsurance === 0">
									</el-input>
								</el-form-item>
								</el-col>
								<el-col :span="24">
									<el-form-item label="状态" prop="status">
										<el-select v-model="addForm.status" placeholder="请选择状态" style="width: 100%">
											<el-option label="启用" value="1"></el-option>
											<el-option label="禁用" value="0"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
							</el-row>
						</el-form>
						<span slot="footer" class="dialog-footer">
							<el-button 
								type="primary" 
								@click="submit" 
								size="mini" 
								:loading="loading">
								{{ editMode ? '保存修改' : '确 定' }}
							</el-button>
							<el-button @click="addMenuDialog = false" size="mini">取 消</el-button>
						</span>
					</el-dialog>
				</div>
		</div>
	</div>
</template>

<script>
	// selfs / sons
	// 在文件顶部导入 pinyin 库
	import { pinyin } from 'pinyin-pro';
	import AccType from './AddType.js'
	import editType from './editType.js'
	import icons from '@/external/icons.js'
	// import * as echarts from "echarts";
	// 接口
	import { addMenu , AllMenu , removeMenu , editMenu } from "@/api/user.js";
	import { adddocclinic,editdocclinic,docclinic,docclinicPage,deleteDocclinic,getClinicDetail } from "@/api/cinic/cinic.js";
	export default {
		inject: ['reload'], // 无痕刷新
		components: {
			
		},
		watch: {
		// 监听医保状态变化
		'addForm.isInsurance'(newVal) {
			if (newVal === 0) {
				// 取消医保时清空医保区划字段
				this.addForm.mdtrtareaAdmvs = '';
			}
			
			// 触发字段重新验证
			this.$nextTick(() => {
				this.$refs.addForm.validateField('mdtrtareaAdmvs');
				this.$refs.addForm.validateField('code');
			});
		}
		},
		data() {
			return {
				idx:'',
				filterText:'',
				searchValue: '',
				selectValue: '',
				// 新增数据项
				dialogTitle: '新增诊所',
				editMode: false,
				currentEditId: null,
				tableHeight: 500, // 初始高度，将在mounted中动态计算
				username:'', // 当前登录用户
				loading: false,
				disabled: true,
				addMenuDialog: false,
				editMenuDialog: false,
				OpenIcons:false, //icons选择
				// 是否展开，默认全部展开
				isExpandAll: false,
				expandedRowKeys: [], // 用于存储默认展开的行的 id
				windowWidth: '',
				pageNum: 1, //当前页currentPage
				pageSize: 20,
				totalSize: 10, //总条数
				// 页面默认按钮// 基础按钮配置（始终显示）
				defaultButtons:[
					{ title:'', icon:"el-icon-refresh" },{ title:'', icon:"el-icon-s-tools" },{ title:'', icon:"el-icon-full-screen" }
				],
				
				// 最终使用的按钮数组
				feetBtn: [],
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				// ...其他原有数据
				// 修改表单数据结构
			   addForm: {
				  address: "",
				  code: "",        // 医疗机构编码
				  expireDate: "", 
				  name: "",
				  pinyin: "",
				  status: "1",
				  isInsurance: 0,  // 新增：是否医保 0-否 1-是
				  mdtrtareaAdmvs: "" // 新增：就医地医保区划
				},
				formType: [],
				statusOptions: [
				  { id: '1', label: '启用' },
				  { id: '0', label: '禁用' }
				],
				pickerOptions: {
				      disabledDate(time) {
				        // 禁用今天之前的日期
				        return time.getTime() < Date.now() - 8.64e7;
				      }
				    },
				elTree:[{ label: '宜宾九阵软件科技有限公司', path:'', title:'', icon:'el-icon-news',
				children:[
						{
							label: '运维部',
							path:'',
							title:'',
							icon:'el-icon-news',
							children:[
								{
									label: '运维一组',
									path:'',
									title:'',
									icon:'el-icon-news',
								},
								{
									label: '运维二组',
									path:'',
									title:'',
									icon:'el-icon-news',
								},
								{
									label: '运维三组',
									path:'',
									title:'',
									icon:'el-icon-news',
								},
							]
						},
						{
							label: '后勤部',
							path:'',
							title:'',
							icon:'el-icon-news',
							children:[
								{
									label: '后勤一部',
									path:'',
									title:'',
									icon:'el-icon-news',
								},
								{
									label: '后勤二部',
									path:'',
									title:'',
									icon:'el-icon-news',
								}
							]
						},
						{
							label: '财务部',
							path:'',
							title:'',
							icon:'el-icon-news',
							children:[
								{
									label: '宜宾一部',
									path:'',
									title:'',
									icon:'el-icon-news',
								},
								{
									label: '成都二部',
									path:'',
									title:'',
									icon:'el-icon-news',
								},
								{
									label: '水富三部',
									path:'',
									title:'',
									icon:'el-icon-news',
								}
							]
						},
						{
							label: '研发部',
							path:'',
							title:'',
							icon:'el-icon-news',
							children:[
								{
									label: '后端',
									path:'',
									title:'',
									icon:'el-icon-news',
									children:[
										{
											label: '后端一组',
											path:'',
											title:'',
											icon:'el-icon-news',
										},
										{
											label: '后端二组',
											path:'',
											title:'',
											icon:'el-icon-news',
										}
									]
								},
								{
									label: '前端',
									path:'',
									title:'',
									icon:'el-icon-news',
									children:[
										{
											label: '前端一组',
											path:'',
											title:'',
											icon:'el-icon-news',
										},
										{
											label: '前端二组',
											path:'',
											title:'',
											icon:'el-icon-news',
										}
									]
								},
								{
									label: '设计',
									path:'',
									title:'',
									icon:'el-icon-news',
									children:[
										{
											label: 'UI一部',
											path:'',
											title:'',
											icon:'el-icon-news',
										},
										{
											label: '平面二部',
											path:'',
											title:'',
											icon:'el-icon-news',
										}
									]
								},
							]
						}
					] ,
				}],
				options: [{value: '可用',label: '可用'},{value: '禁用',label: '禁用'}],
				// header查询重置按钮
				headerBtn:[{ title:"刷新", icon:"el-icon-refresh" }],
				headerBtnbottomRight:[{ icon:"el-icon-refresh" },{ icon:"el-icon-s-tools" },{ icon:"el-icon-full-screen" }],
				edits:[{ title:"修改",type:'primary' },{ title:"新增",type:'primary' },{ title:"删除",type:'danger' },],
				// 表格行
				tableRows:[
					{ name:"诊所名称", prop:"name", type:"" },
					{ name:"编码", prop:"code", type:"" },{ name:"拼音简码", prop:"pinyin", type:"" },
					{ name:"诊所地址", prop:"address", type:"" },
					{ name:"创建时间", prop:"createTime", type:"" },{ name:"更新时间", prop:"updateTime", type:"" },
				],
				
				// 表单
				// formType:[],
				editFormType:[],
				// icons
				icons:[],
				// 表格data
				tableData:[],
				restaurants:[],
				selectOptions:[],
				// 修改表单
				editForm:{
					menuId:'', //菜单id
					menuName:'', //菜单名称
					parentId:'', //菜单父id => 上级菜单
					type:'', //菜单类型（M目录 C菜单 F按钮）
					component:'', //组件名称
					icon:'', //菜单icon
					orderNum:'', //排序号
					path:'', //菜单路径
					isInsurance: 0,  // 新增：是否医保 0-否 1-是
					mdtrtareaAdmvs: "" // 新增：就医地医保区划
				},
				// ...其他数据
				addFormRules: {
				  name: [
					{ required: true, message: '请输入诊所名称', trigger: 'blur' }
				  ],
				  code: [
					{ 
					  required: true, 
					  message: '请输入医疗机构编码', 
					  trigger: 'blur',
					  // 条件验证：仅当医保选中时必填
					  validator: (rule, value, callback) => {
						if (this.addForm.isInsurance == 1 && !value) {
						  callback(new Error('医疗机构编码为必填项'));
						} else {
						  callback();
						}
					  }
					}
				  ],
				  expireDate: [
					{ required: true, message: '请选择过期日期', trigger: 'change' }
				  ],
				  isInsurance: [
					{ required: true, message: '请选择是否医保', trigger: 'change' }
				  ],
				  mdtrtareaAdmvs: [
					{ 
					  required: true, 
					  message: '请输入就医地医保区划', 
					  trigger: 'blur',
					  // 条件验证：仅当医保选中时必填
					  validator: (rule, value, callback) => {
						if (this.addForm.isInsurance == 1 && !value) {
						  callback(new Error('就医地医保区划为必填项'));
						} else {
						  callback();
						}
					  }
					}
				  ],
				  status: [
					{ required: true, message: '请选择状态', trigger: 'change' }
				  ],
				}
			}
		},
		mounted() {
			// 左侧提交表单
			this.formType = AccType.map(function(v) {
				return v
			})
			this.calculateTableHeight();
			window.addEventListener('resize', this.calculateTableHeight);
			// 左侧修改提交表单
			this.editFormType = editType.map(function(v) {
				return v
			})
			// 获取会话存储从钩子函数上获取到数据
			this.loadData();
			this.username = JSON.parse(localStorage.getItem('userInfo')).username
			// console.log(this.username);
			//获取动态盒子宽度，实时赋值给右侧 => this.$refs.mainRight.offsetWidth;
			this.$nextTick(()=>{
				this.initButtons(); // 引入全局自定义封装方法
				this.updateWindowWidth();
				window.addEventListener('resize', this.updateWindowWidth);
			})
		},
		// 在beforeDestroy中移除监听
		beforeDestroy() {
		  window.removeEventListener('resize', this.calculateTableHeight);
		},
		methods:{
			async loadData(){
				// 所有菜单
				let res = await docclinicPage({
					name:this.name,
					pageNum:this.pageNum,
					pageSize:this.pageSize,
				});
				console.log(res,'resres');
				this.totalSize = res.data.totalSize
				this.tableData = res.data.content
				// 将菜单里还未新增之前的数据源存放于会话，以便角色默认使用。
				// sessionStorage.setItem('MenuForRoleItems', JSON.stringify(this.tableData))
				this.restaurants = this.tableData.map(item =>{
					return { value:item.name , ...item }
				})
			},
			// 权限按钮
			initButtons() {
			    // 获取当前路由路径
			    const currentPath = this.$route.path;
			    // 获取路由对应的权限按钮
			    const routeButtons = this.$getRouteButtons(currentPath);
			    // 合并到现有按钮数组
			    this.feetBtn = this.$mergeButtons(this.defaultButtons, routeButtons);
				console.log(this.feetBtn,'feetBtnfeetBtn');
			},
			// 视口高度
			calculateTableHeight() {
				const windowHeight = window.innerHeight;
				const headerHeight = 40; // 标题高度
				const searchHeight = 40; // 搜索栏高度
				const paginationHeight = 60; // 分页高度
				const margin = 30; // 其他边距
				
				this.tableHeight = windowHeight - headerHeight - searchHeight - paginationHeight - margin;
			},
			// 搜索建议
			querySearch(queryString, cb) {
				var restaurants = this.restaurants;
				var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
				// 调用 callback 返回建议列表的数据
				cb(results);
			},
			createFilter(queryString) {
				return (restaurant) => {
				  return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
				};
			},
			handleSelect(item) {
			    this.tableData = [];
				this.tableData.push(item)
			},
			// 计数器
			handleChange(value) {
				console.log(value);
			},
			
			// 生成拼音简码（改进版）
			  generatePinyin() {
			    if (this.addForm.name) {
			      // 每次失去焦点都重新生成拼音简码
			      this.addForm.pinyin = this.makePy(this.addForm.name);
			    }
			  },
			  // 当名称变化时清除拼音简码
			  clearPinyinIfNameChanged() {
				this.addForm.pinyin = '';
			  },
			  // 拼音转换方法
			  makePy(str) {
			    if (!str) return '';
			    try {
			      // 使用 pinyin-pro 获取拼音首字母
			      const result = pinyin(str, {
			        pattern: 'first',  // 只获取首字母
			        toneType: 'none',  // 不带声调
			        type: 'array'      // 返回数组
			      });
			      
			      // 将数组转换为字符串并处理
			      return result.join('')
			        .substring(0, 6)   // 取前6个字符
			        .toUpperCase();     // 转换为大写
			    } catch (error) {
			      console.error('生成拼音出错:', error);
			      return '';
			    }
			  },
			// // 提交新增表单
			//  async submit() {
			//     // 先进行表单验证
			//     this.$refs.addForm.validate(async (valid) => {
			//       if (valid) {
			//         try {
			//           this.loading = true;
			//           let res = await adddocclinic(this.addForm);
			          
			//           if (res.code === 200) {
			//             this.$message.success('新增诊所成功！');
			//             this.addMenuDialog = false;
			//             this.loadData();
			//           } else {
			//             this.$message.error(res.message || '新增失败');
			//           }
			//         } catch (error) {
			//           console.error(error);
			//           this.$message.error('请求失败');
			//         } finally {
			//           this.loading = false;
			//         }
			//       } else {
			//         this.$message.warning('请填写完整表单信息');
			//         return false;
			//       }
			//     });
			//   },
			/*
				about tree
			*/
			handleNodeClick(data,e) {
				this.CatalogueName = data.title
				this.iconComes = 'el-icon-' + this.makePy(data.label)
				// console.log(this.iconComes);
				// this.loadData();
			},
			// 过滤器
			filterNode(value, data) {
				if (!value) return true;
				return data.label.indexOf(value) !== -1;
			},
			handleClose(done) {
				this.$confirm('确认关闭？')
				  .then(_ => {
				done();
			  })
			  .catch(_ => {});
			},

			// 重置表单方法修改
			resetAddForm() {
			  this.addForm = {
				address: "",
				code: "",
				expireDate: "",
				name: "",
				pinyin: "",
				status: "1",
				isInsurance: 0,      // 默认不选中医保
				mdtrtareaAdmvs: ""   // 清空医保区划
			  };
			  this.editMode = false;
			  this.dialogTitle = '新增诊所';
			  this.currentEditId = null;
			},
			// 步骤
			handClick(i) {
				// i event
				switch (i) {
					case 0:
						// 处理索引0的逻辑 页面刷新
						this.loading = true;
						setTimeout(() => {
							this.reload();
							this.$message({type:'success',message:'已刷新'})
							this.loading = false;		
						}, 1500)
						break;
					case 1:
						// 处理索引1的逻辑
						this.$confirm('敬请期待')
							.then(_ => {})
							.catch(_ => {});
						break;
				}
			},
			feetHandClick(v,i){
				console.log(v,i,'ssssssssssssssssss');
				// 获取当前操作按钮
				const button = this.feetBtn[i];
				// 如果按钮被禁用，直接返回
				if (button.disabled) {
					this.$message.warning('当前操作不可用');
					return;
				}
				// 处理逻辑 => 新增
				else if(v.title == '新增' || v.title.includes('新增') || v.title.includes('新建')){
					// 处理索引2的逻辑 => 新增 -> 调用子组件
					this.addMenuDialog = true;
					this.resetAddForm(); // 重置表单
				}
				// 处理逻辑 => 未知错误
				else{
					this.$message({ type: 'danger', message: this.undefind });
				}
				// i event
			},
			//  select聚焦
			async sname(v,i) {
				// v.id = i;
				// console.log(v,i);
				// this.idx = i;
				// i event
				switch (i) {
					case 1:
						// 父级菜单Id
						let res = await AllMenu();
						this.selectOptions = res.rows.children
						break;
				}
			},
			// 编辑按钮点击事件
			async handleEdit(row) {
			  this.editMode = true;
			  this.dialogTitle = '编辑诊所';
			  this.currentEditId = row.id;
			  this.addMenuDialog = true;
			  
			  try {
			    this.loading = true;
			    // 调用接口获取详情数据 - 直接传递ID而不是对象
			    const res = await getClinicDetail(row.id);
			    if (res.code === 200) {
			      // 将接口数据填充到表单
			      this.addForm = {
			        ...this.addForm,
			        ...res.data
			      };
			    } else {
			      this.$message.error(res.message || '获取详情失败');
			    }
			  } catch (error) {
			    console.error(error);
			    this.$message.error('请求失败');
			  } finally {
			    this.loading = false;
			  }
			},
			    
			// 提交表单方法修改
			async submit() {
			  this.$refs.addForm.validate(async (valid) => {
			    if (valid) {
			      try {
			        this.loading = true;
			        
			        // 准备提交数据
			        const submitData = {
			          ...this.addForm,
			          // 确保日期格式正确
			          expireDate: this.addForm.expireDate || ''
			        };
			        
			        let res;
			        if (this.editMode) {
			          res = await editdocclinic({
			            id: this.currentEditId,
			            ...submitData
			          });
			        } else {
			          res = await adddocclinic(submitData);
			        }
			        
			        if (res.code === 200) {
			          this.$message.success(this.editMode ? '修改成功' : '新增成功');
			          this.addMenuDialog = false;
			          this.loadData();
			        } else {
			          this.$message.error(res.message || '操作失败');
			        }
			      } catch (error) {
			        console.error(error);
			        this.$message.error('请求失败');
			      } finally {
			        this.loading = false;
			      }
			    } else {
			      this.$message.warning('请填写完整表单信息');
			      return false;
			    }
			  });
			},
			// SelectVal to editForm

			// col 里面包含了表头字段和名称，list 是表格数据
			columnWidth(col, list) {
			    if (!col.prop || !list || list.length === 0) return 120; // 默认宽度
			    
			    let prop = col.prop;
			    let label = col.name || '';
			    let maxContentWidth = 0;
			    
			    // 计算表头宽度
			    let headerWidth = this.calculateTextWidth(label) + 24; // 加上padding
			    
			    // 计算内容最大宽度
			    list.forEach(item => {
			      let content = item[prop] || '';
			      let contentWidth = this.calculateTextWidth(content.toString());
			      if (contentWidth > maxContentWidth) {
			        maxContentWidth = contentWidth;
			      }
			    });
			    
			    // 取表头和内容最大宽度，加上padding和border
			    return Math.max(headerWidth, maxContentWidth) + 24;
			  },
			  
			  calculateTextWidth(text) {
			    // 创建一个临时元素来计算文本宽度
			    let span = document.createElement('span');
			    span.style.visibility = 'hidden';
			    span.style.whiteSpace = 'nowrap';
			    span.style.fontSize = '12px';
			    span.style.fontFamily = 'Microsoft YaHei';
			    span.innerHTML = text;
			    document.body.appendChild(span);
			    let width = span.offsetWidth;
			    document.body.removeChild(span);
			    return width;
			},
			// db events
			handledbRow(row, column, event){
				console.log(row);
			},
			//分页
			//每页条数改变触发
			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.pageNum = val;
				this.loadData();
			},
			//当前条数改变触发
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.pageNum = val;
				this.loadData();
			},
			// 实时宽度
			updateWindowWidth() {
			    this.windowWidth = window.innerWidth - 228;
			},
			toggleExpand(row) {
				 this.$refs.table.toggleRowExpansion(row);
				 row.expanded = !row.expanded
			},
			// 修改提交
			async editSubmit(){
				let rs = await editMenu(this.editForm);
				if(this.editForm.type === '目录'){
					this.editForm.type = 'M'
				}else if(this.editForm.type === '菜单'){
					this.editForm.type = 'C'
				}else if(this.editForm.type === '按钮'){
					this.editForm.type = 'F'
				}else{
					this.editForm.type = 'UNDEFIND'
				}
				console.log(this.editForm);
				if (rs.code === 200) {
					this.$message({
						type: 'success',
						message: '菜单修改成功！',
					});
					//更新数据源
					this.loadData();
					// 动态设置默认展开的行
					this.expandedRowKeys.push(this.editForm.menuId); // 设置默认展开的行的 id
					this.editMenuDialog = false;
				} else {
					this.$message.error(res.message)
				}
			},
			//删除菜单
			handleDelete(id) {
			  this.$confirm("此操作将永久删除该菜单, 是否继续?", "提示", {
			    confirmButtonText: "确定",
			    cancelButtonText: "取消",
			    type: "warning",
			  }).then(() => {
				  this.$prompt('请验证当前用户' + this.username + '的密码', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					inputErrorMessage: '邮箱格式不正确'
				  }).then(async({ value }) => {
					let pwd = JSON.parse(localStorage.getItem('userInfo')).salt
					if( value == pwd){
						let res = await deleteDocclinic({ ids:id })
						if (res.code === 200) {
						   this.$message({
							 type: "success",
							 message: res.message,
						   });
						   this.loadData(); //重新加载数据页面
						} else {
						   this.$message.error(res.message);
						}
					}else{
						this.$message({type:'error',message:'验证失败!'})
					}
					
				  }).catch(() => {
					this.$message({
					  type: 'info',
					  message: '取消输入'
					});       
				});
				}).catch(() => {
			      console.log("取消");
			    });
			},
		},
		watch: {
			windowWidth(newVal) {
			  console.log('New window width:', newVal);
			  // 在这里执行逻辑，例如重新布局等。
			}
		}
	}
</script>

<style lang="less" scoped>
	// 穿透
	/deep/ .el-table .cell{
		font-size: 12px;
		text-overflow: ellipsis;
		white-space: nowrap;
		// border: 1px solid #007bb0;
		overflow: hidden;
	}
	/deep/ .el-table th{
		font-size: 12px;
		// background-color: #f1f1f1;
		// border: 1px solid #007bb0;
		color: #2d2d2d;
	}
	/deep/ .el-table {
	  width: 100% !important;
	  min-width: auto !important;
	  
	  .el-table__body-wrapper {
	    overflow-x: auto !important;
	    overflow-y: auto !important;
	  }
	  
	  .el-table__header-wrapper {
	    // overflow-x: scroll !important;
	    // padding-bottom: 17px !important; /* 为滚动条留出空间 */
	  }
	    
	    &::before {
	      display: none;
	    }
	    
	    .el-table__empty-block {
	      background-color: transparent;
	    }
	    // height: 100% !important;
	    .el-table__body-wrapper {
	      overflow-x: hidden;
	    }
	}
	/deep/ .el-dialog__header{
		padding: 12px;
		background-color: #007bb0;
	}
	/deep/ .el-dialog__title{
		font-size: 12px;
		color: #fff;
	}
	/deep/ .el-dialog__headerbtn .el-dialog__close{
		color: #fff;
	}
	.user{
		width: 100%;
		height: 100%;
		background-color: #fff;
		.contentMain{
		
			.title{
				height: 40px;
				line-height: 40px;
				span{
					font-weight: 300;
					margin-left: 12px;
				}
			}
			.main{
				width: 100%;
				margin-top: 8px;
				// display: flex;
				.main-right{
					margin-left: 12px;
					.searchValue{
						display: flex;
						justify-content: space-between;
						/deep/ .el-input{
							width: 188px;
						}
						/deep/ .el-select{
							margin-left: 8px;
						}
						/deep/ .el-button{
							margin-left: 8px;
						}
						.leftBtn{
							// display: flex;
							// justify-content: space-around;
						}
					}
					.content{
						display: flex;
						justify-content: center;
						// height: 430px;
						width: 100%;
						margin-top: 12px;
						border: 1px solid #dddddd;
						border-radius: 4px;
						/deep/ .el-table .cell{
							font-size: 12px;
							text-align: center;
						}
						/deep/ .el-table--border .el-table__cell, .el-table__body-wrapper .el-table--border.is-scrolling-left~.el-table__fixed{
							border: 0;
						}
						/deep/ .el-table{
							// background-color: #fff;
						}
						/deep/ td {
							padding: 0!important;
							height: 32px;
						}
						/deep/ .el-table td.el-table__cell div :first-child{
							text-align: center;
						}
						
					}
					.foot{
						display: flex;
						justify-content: flex-end;
						margin-top: 8px;
					}
					
				}
			}
			.addMenuDiglog {
			  /deep/ .el-dialog__body {
			    padding: 10px 20px;
			  }
			  /deep/ .el-form-item {
			    margin-bottom: 12px;
			  }
			  /deep/ .el-form-item__label {
			    font-size: 12px;
			  }
			}
			.editMenuDiglog{
				.icon-list {
				  display: flex;
				  flex-wrap: wrap;
				  justify-content: space-around;
				}
				
				.icon-item {
				  display: flex;
				  justify-content: center;
				  flex-direction: column;
				  align-items: center;
				  width: 68px;
				  height: 68px;
				  margin: 4px;
				  border: 1px solid #ccc;
				  border-radius: 4px;
				  cursor: pointer;
				}
				
				.icon-item:hover {
				  background-color: #f5f7fa;
				}
			}
		}
	}
</style>